package com.strive.village.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.strive.village.common.Result;
import com.strive.village.entity.TbResident;
import com.strive.village.entity.TbVillage;
import com.strive.village.entity.dto.ResidentDto;
import com.strive.village.exception.EasyExcelException;
import com.strive.village.utils.DBExportUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author strivePeng
 * @since 2024-04-18
 */
@RestController
@RequestMapping("/sys/resident")
public class TbResidentController extends BaseController {

    // 日志输出
    private static final Logger logger = LoggerFactory.getLogger(TbResidentController.class);

    /**
     * 分页查询所有村民信息
     *
     * @param rName 村民名
     * @return 查询列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:resident:list')")
    public Result getResidentList(String rName) {
        Page<TbResident> pageData = residentService.page(getPage(), new QueryWrapper<TbResident>().like(StrUtil.isNotBlank(rName), "name", rName));
        return Result.success(pageData);
    }

    /**
     * 根据ID查询村民信息
     *
     * @param residentId 村民ID
     * @return 一条村民信息
     */
    @GetMapping("/info/{residentId}")
    @PreAuthorize("hasAuthority('sys:resident:list')")
    public Result getVillageInfo(@PathVariable(name = "residentId") Long residentId) {
        TbResident resident = residentService.getById(residentId);
        return Result.success(resident);
    }


    /**
     * 保存一条村民信息
     *
     * @param resident 前端传来的村民信息
     * @return msg消息
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:resident:save')")
    public Result saveVillage(@RequestBody TbResident resident) {
        residentService.save(resident);
        return Result.success("添加成功");
    }

    /**
     * 更新一条村民信息
     *
     * @param resident 前端传来的村民信息
     * @return msg消息
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:resident:update')")
    public Result updateVillage(@RequestBody TbResident resident) {
        residentService.updateById(resident);
        return Result.success("更新成功");
    }

    /**
     * 删除村民信息
     *
     * @param residentIds 前端传来的村民IDs
     * @return msg消息
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:resident:delete')")
    public Result deleteVillage(@RequestBody Long[] residentIds) {
        residentService.removeByIds(Arrays.asList(residentIds));
        // 删除关联表 数据库村民表外键自动删除
        return Result.success("删除成功");
    }

    /**
     * 根据不同的年龄段返回村民人数
     */
    @GetMapping("/countByAge")
    public Result getCountByAgeRange(int ageRangeStart, int ageRangeEnd) {
        int count = residentMapper.getResidentCountByAge(ageRangeStart, ageRangeEnd);
        return Result.success(count);
    }

    // 文件导出路径
    @Value("${export.file.path}")
    private String exportPath;

    /**
     * 文件导出接口
     *
     * @return 返回导出信息
     */
    @GetMapping("/export")
    public Result exportResidentInfo() {
        // 使用DTO类导出
        try {
            List<TbResident> residentList = residentService.list();
            if (residentList.isEmpty()) {
                return Result.fail("文件为空");
            } else {
                List<ResidentDto> dtoList = new ArrayList<>();
                // 循环读取数据 转化为DTO
                residentList.forEach(r -> {
                    ResidentDto dto = new ResidentDto();
                    dto.setName(r.getName());
                    dto.setAge(r.getAge());
                    dto.setGender(r.getGender());
                    dto.setContactNumber(r.getContactNumber());
                    dto.setOccupation(r.getOccupation());

                    TbVillage village = villageService.getById(r.getVillageId());
                    dto.setVillageName(village.getVillageName());

                    dtoList.add(dto);
                });
                DBExportUtils.exportResidentToExcel(dtoList, exportPath);
                return Result.success(MapUtil.builder()
                        .put("filePath", exportPath)
                        .build());
            }
        } catch (EasyExcelException e) {
            // 打印日志
            logger.error(e.getMessage(), e);
            throw new EasyExcelException(e.getMessage(), e);
        }
    }

    /**
     * 文件导入接口
     *
     * @param file 前段传来的文件
     * @return 返回导出结果
     */
    @PostMapping("/upload")
    public Result importResidentInfo(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("上传文件为空");
        } else {
            try (InputStream inputStream = file.getInputStream()) {
                // 读取文件内容
                EasyExcel.read(inputStream, ResidentDto.class, residentUploadUtils).sheet().doRead();
                return Result.success("文件导入成功");
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw new EasyExcelException("文件上传失败", e);
            }
        }
    }
}
